#!/usr/bin/env python
# encoding=utf-8
import sys

from fuzzywuzzy import fuzz
from pymongo import MongoClient
from scpy.logger import get_logger
from xtls.timeparser import now
from xtls.util import sha1

from config import *
from util import query_location

reload(sys)
sys.setdefaultencoding('utf-8')

__author__ = 'xlzd'
logger = get_logger(__file__)
MONGO = MongoClient(MONGO_HOST, MONGO_PORT)


def calc_id(item):
    return sha1(u'%s-%s-%s' % (item['officeDistrict'], item['building'], item['grade']))


def match_loaction(item):
    # if item['building'] == u'朗晴国际甲级写字楼':
    #     locations = query_location(item['officeDistrict'].split('#')[0], u'朗晴国际')
    # else:
    #     locations = query_location(item['officeDistrict'].split('#')[0], item['building'])
    # locations = query_location(item['officeDistrict'].split('#')[0], item['building'])
    # if not locations or 'location' not in locations[0]:
    #     locations = query_location(item['officeDistrict'].split('#')[0], item['address'])
    locations = query_location(item['officeDistrict'].split('#')[0], item['address'].split('#')[0])
    # print json.dumps(locations, ensure_ascii=False, indent=4, sort_keys=True)
    nowmax_score, nowmax_place = -1, None
    for place in locations:
        score = 0
        if item['address'] in place['address'] or place['address'] in item['address']:
            score += 1
        else:
            score += (fuzz.ratio(item['address'], place['address']) / 100.)

        tag = place.get('detail_info', {'tag': ''}).get('tag', '')
        if u'写字楼' in tag or u'公司' in tag or u'企业' in tag:
            score += 0.5
        elif u'房地产' in tag:
            score += 0.3

        if item['building'] in place['name'] or place['name'] in item['building']:
            score += 1
        else:
            score += (fuzz.ratio(item['building'], place['name']) / 100.)

        if nowmax_score < score:
            nowmax_score = score
            nowmax_place = place
    # print json.dumps(nowmax_place, ensure_ascii=False, indent=4, sort_keys=True)
    if not nowmax_place:
        return None, None
    return nowmax_place['location']['lat'], nowmax_place['location']['lng']


def calc_price():
    err = saved = 0
    for index, item in enumerate(MONGO[DB_NAME]['officeBuilding'].find({'coordinate': [-1, -1]}).batch_size(100), start=1):
        _id = calc_id(item)
        logger.info('now index %s, now item %s' % (index, item['building']))
        if MONGO[DB_NAME]['officeBuildingError'].find_one({'_id': _id}):
            continue
        try:
            lat, lng = match_loaction(item)  # 纬度、经度
            if not lat:
                raise Exception('got %s-%s-%s' % (lat, lng, item))
        except Exception, e:
            MONGO[DB_NAME]['officeBuildingError'].find_one_and_update(
                filter={'_id': _id},
                update={'$set': {
                    '_id': _id,
                    'building': item['building'],
                    'grade': item['grade'],
                    'address': item['address'],
                    'officeDistrict': item['officeDistrict'],
                    'totalFloor': item['totalFloor'],
                    'coordinate': [-1, -1],
                    'averagePrice': 0,
                    'sampleCount': 0
                }},
                upsert=True
            )
            err += 1
            logger.info('error times %s-%s' % (err, item))
            logger.exception(e)
            continue
        building = {
            '_id': _id,
            'building': item['building'],
            'grade': item['grade'],
            'address': item['address'],
            'officeDistrict': item['officeDistrict'],
            'totalFloor': item['totalFloor'],
            'coordinate': [lat, lng],
            'averagePrice': 0,
            'sampleCount': 0,
            'updateTime': now()
        }
        MONGO[DB_NAME]['officeBuilding'].find_one_and_update({'_id': _id}, {'$set': building}, upsert=True)


def find_buildings():
    saved = 0
    for index, item in enumerate(MONGO[DB_NAME]['officeItems'].find().batch_size(100), start=1):
        _id = calc_id(item)
        logger.info('now index %s, now item %s' % (index, item['building']))
        if MONGO[DB_NAME]['officeBuilding'].find_one({'_id': _id}):
            saved += 1
            continue
        building = {
            '_id': _id,
            'building': item['building'],
            'grade': item['grade'],
            'address': item['address'],
            'officeDistrict': item['officeDistrict'],
            'totalFloor': item['totalFloor'],
            'coordinate': [-1, -1],
            'averagePrice': 0,
            'sampleCount': 0,
            'updateTime': now()
        }
        MONGO[DB_NAME]['officeBuilding'].find_one_and_update({'_id': _id}, {'$set': building}, upsert=True)
        # raw_input('go on')


if __name__ == '__main__':
    # find_buildings()
    calc_price()
